<?php

namespace App\Http\Controllers;

use App\Common\Machine\PlayerQueue;
use App\Events\SpectatorsChanged;
use App\Http\Resources\GameRecords;
use App\Http\Resources\Machine as MachineResource;
use App\Http\Resources\MachineCollection;
use App\Models\Machine;
use App\Services\Doll;
use Illuminate\Http\Request;

class MachinesController extends Controller
{
    /**
     * 游戏机列表
     *
     * @return MachineCollection
     */
    public function index()
    {
        $perPage = per_page();

        $paginate = Machine::whereIn('device_status', [
            Machine::DEVICE_STATUS_IDLE,
            Machine::DEVICE_STATUS_WORKING,
        ])->where('is_display', 1)->with('cameras')->orderByDesc('stick_time')
            ->orderByDesc('id')->simplePaginate($perPage);

        return new MachineCollection($paginate);
    }

    /**
     * 游戏机详情
     *
     * @param Machine $machine
     * @return \App\Http\Resources\Machine
     */
    public function show(Machine $machine)
    {
        $machine->load(['cameras', 'latestUser']);

        // 排队的玩家
        $playerQueue = new PlayerQueue($machine);
        $params = [
            'queue_length' => $playerQueue->length(),
        ];

        return new MachineResource($machine, $params);
    }
    
    /**
     * 当“硬件系统”的设备状态发生变化时，会进行通知回调
     *
     * @param \Illuminate\Http\Request $request
     * @param \App\Services\Doll $doll
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, Doll $doll)
    {
        $inputs = $request->all();
        
        if (! $doll->checkSign($inputs['sign'], $inputs)) {
            return invalidation('签名验证失败');
        } elseif (! isset($inputs['device_status'])) {
            // 没有设备状态的话，不做处理
            return;
        }
        
        $where = ['device_id' => $inputs['device_id']];
        
        // 通知的 device_status 值为 1：机器故障，2：机器恢复
        // 为防止对“工作中”的设备业务有影响，只对“空闲”、“故障”的设备进行设备状态更新
        if (2 == $inputs['device_status']) {
            // 修改“故障”设备的状态为“空闲”
            $where['device_status'] = Machine::DEVICE_STATUS_FAULT;
            
            Machine::where($where)->update(['device_status' => Machine::DEVICE_STATUS_IDLE]);
        } else {
            // 修改“空闲”设备的状态为“故障”
            $where['device_status'] = Machine::DEVICE_STATUS_IDLE;
            
            Machine::where($where)->update(['device_status' => Machine::DEVICE_STATUS_FAULT]);
        }
    }

    /**
     * 游戏机抓取记录
     *
     * @param Machine $machine
     * @return GameRecords
     */
    public function gameRecords(Machine $machine)
    {
        $paginate = $machine->gameRecords()->with('user')->orderByDesc('id')->simplePaginate(per_page());
        return new GameRecords($paginate);
    }
    
    /**
     * 进入、退出房间
     *
     * @param \App\Models\Machine $machine
     */
    public function room(Machine $machine)
    {
        event(new SpectatorsChanged($machine));
    }
}
